package zgame.socket.handle;

import org.apache.log4j.Logger;

import zgame.bussiness.AuthenticateBussiness;
import zgame.bussiness.ChatBussiness;
import zgame.socket.DataPackage;
import zgame.socket.ProtocolConstants;
import zgame.socket.server.ServerConnection;

public class ClientRequestHandle implements Runnable {
  private static final Logger log = Logger.getLogger(ClientRequestHandle.class);
  
  private ServerConnection server;
  private DataPackage dataPackage;

  public ClientRequestHandle(ServerConnection server, DataPackage dataPackage) {
    this.server = server;
    this.dataPackage = dataPackage;
  }

  @Override
  public void run() {
    int header = dataPackage.getHeader();

    if (header == ProtocolConstants.RequestHeader.HEART_BREATH_REQUEST) {
      // Do nothing
      return;
    }

    // If user did not authenticate yet
    if (server.user == null) {
      switch (header) {
      /** Authenticate */
      case ProtocolConstants.RequestHeader.AUTHENTICATE_REQUEST:
        AuthenticateBussiness.requestSalt(server, dataPackage);
        break;
      case ProtocolConstants.RequestHeader.AUTHENTICATE_WITH_SESSION_ID_REQUEST:
        AuthenticateBussiness.authenticateBySessionId(server, dataPackage);
        break;
      }
      return;
    }

    // If user already authenticate
    switch (header) {
    case ProtocolConstants.RequestHeader.CHAT_CREATE_ROOM_REQUEST:
      ChatBussiness.onCreateRoomRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_JOIN_CHAT_ROOM_REQUEST:
      ChatBussiness.onJoinChatRoomRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_SEND_MESSAGE_REQUEST:
      ChatBussiness.onSendMessageRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_CHANGE_ROOM_PASSWORD_REQUEST:
      ChatBussiness.onChangeRoomPasswordRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_KICK_MEMBER_REQUEST:
      ChatBussiness.onKickMemberRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_INVITE_CHAT_REQUEST:
      ChatBussiness.onInviteChatRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_BLOCK_USER_REQUEST:
      ChatBussiness.onBlockUserRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_ROOM_LIST_REQUEST:
      ChatBussiness.onChatRoomListRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_LEAVE_ROOM_REQUEST:
      ChatBussiness.onUserLeaveRoomRequest(server, dataPackage);
      break;
    case ProtocolConstants.RequestHeader.CHAT_ROOM_MEMBER_LIST_REQUEST:
      ChatBussiness.onRoomMemberListRequest(server, dataPackage);
      break;
    default:
      log.warn("Received unknown package header: " + header);
      break;
    }
  }
}
